var menuList = getSettingsMenuList(),
	langList = getLangList(),
	doms = {
		name: null,
		userId: null,
		avatar: null,
		exit: null
	},
	settingsMenu = null,
	langRadioGroup = null,
	selectLanguagePanel = null;

$(() => {
	initDoms();
	initSelectLangPanel();
	queryUserInfo();
	queryCache();
	initMenu();
})

initDoms = () => {
	doms.name = document.getElementById('name');
	doms.userId = document.getElementById('user_id');
	doms.avatar = document.getElementById('avatar');
	doms.exit = document.getElementById('exit');
	document.getElementById('exit').addEventListener('click', e => {
		onExit();
	})
	document.getElementById('user_info').addEventListener('click', e => {
		navigateTo(`page/user/personal.html`)
	})
}

initSelectLangPanel = () => {
	selectLanguagePanel = new LanguagePanel({
		data: getLangList(),
		defaultLanguage: localStorage.getItem('appLanguage') || 'zh',
		onLanguageChange: (lang) => {
			showToast('切换成功！');
		}
	});
}

queryUserInfo = () => {
	let subLoading = layer.open({
		type: 2,
		content: getStartText()
	});
	setTimeout(() => {
		layer.close(subLoading);
		getUserInfo({}, res => {
			setUserInfo(res);
		})
	}, 1000)
}

setUserInfo = e => {
	const {
		name,
		id,
		avatar
	} = e;
	doms.name.innerHTML = name;
	doms.userId.innerHTML = `吃货号：` + id;
	doms.avatar.src = avatar;
}

initMenu = () => {
	settingsMenu = new Menu({
		data: menuList,
		container: "#menu",
		onClickItem: (item) => {
			handleMenuItem(item)
		},
		onSwitchChange: res => {
			openOrCloseNotice(res);
		}
	})
}

const handleMenuItem = async ({
	key,
	url
}) => {
	try {
		switch (key) {
			case 'cache':
				await cleanCache();
				break;
				// case 'notice':
				// 	await openOrCloseNotice();
				// 	break;
			case 'lang':
				await onSwitchLang();
				break;
			default:
				url && await navigateTo(`${url}.html`);
		}
	} catch (error) {
		console.error('菜单处理失败:', error);
	}
};

queryCache = () => {
	let subLoading = layer.open({
		type: 2,
		content: getStartText()
	});
	setTimeout(() => {
		layer.close(subLoading);
		let cacheData = {
			key: 'cache',
			value: '52.7M'
		};
		updateCache(cacheData);
	}, 500)
}

cleanCache = () => {
	let subLoading = layer.open({
		type: 2,
		content: '正在清除...'
	});
	setTimeout(() => {
		layer.close(subLoading);
		showToast('清除成功！');
		let cacheData = {
			key: 'cache',
			value: '0M'
		};
		updateCache(cacheData);
	}, 1000)
}

updateCache = (cacheItem) => {
	let cacheObj = menuList.find(e => e.key == cacheItem.key);
	cacheObj.value = cacheItem.value;
	settingsMenu.update(menuList)
}

openOrCloseNotice = (item) => {
	let subLoading = layer.open({
		type: 2,
		content: '正在设置...'
	});
	setTimeout(() => {
		layer.close(subLoading);
		showToast('设置成功！');
	}, 1000)
}

onSwitchLang = () => {
	selectLanguagePanel.open();
}

onExit = () => {
	navigateTo(`login.html`)
}
